package com.open.demo.location

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import java.util.*


/**
 *
 * @Author: hailong.qiu hailong.qiu@xgimi.com
 * @Maintainer: hailong.qiu hailong.qiu@xgimi.com
 * @Date: 2021/7/5
 * @Copyright: 2021 www.xgimi.com Inc. All rights reserved.
 */
class GpsActivity : Activity() {

    companion object {
        const val TAG = "GPS Demo"
        const val REQUEST_STORAGE_PERMISSION = 250
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                REQUEST_STORAGE_PERMISSION
            );
            return
        }
        //
//        getLocation()
        initLocation()
    }

    @SuppressLint("MissingPermission")
    private fun initLocation() {
        val locationManger:LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val providerList = locationManger.getProviders(true)
        var locationProvider: String = ""
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            locationProvider = LocationManager.GPS_PROVIDER
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        val location = locationManger.getLastKnownLocation(locationProvider)
        Log.d(TAG, "initLocation providerList:${providerList} locationProvider:${locationProvider} location:${location}")
//        locationManger.requestLocationUpdates(locationProvider, 5000, 10F, newLocationListener)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Log.d(TAG, "====onRequestPermissionsResult===>>> requestCode:$requestCode permissions:$permissions grantResults:$grantResults")
    }

    @SuppressLint("MissingPermission")
    fun getLocation() {
        val locationManger:LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val providerList = locationManger.getProviders(true)
        var locationProvider: String = ""
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            Log.d(TAG, "====GPS_PROVIDER===>>> GPS 定位的精准度比较高，但是非常耗电。")
            locationProvider = LocationManager.GPS_PROVIDER
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            Log.d(TAG, "====NETWORK_PROVIDER===>>> 网络定位的精准度稍差，但耗电量比较少。(Google服务被墙不可用)")
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Log.d(TAG, "=====NO_PROVIDER=====>>> 当没有可用的位置提供器时，弹出Toast提示用户");
        }

        // 获取上次的位置，一般第一次运行，此值为null
        val location = locationManger.getLastKnownLocation(locationProvider)
        if (null != location) {
            Log.d(TAG, "====显示当前设备的位置信息==== $location");
            showLocation(location)
        } else {
            Log.d(TAG, "====当GPS信号弱没获取到位置的时候可从网络获取(Google服务被墙的解决办法)==== location:$location");
            getLngAndLatWithNetwork();
        }
        //
        locationManger.requestLocationUpdates(locationProvider, 5000, 10F, locationListener)
    }

    @SuppressLint("MissingPermission")
    private fun getLngAndLatWithNetwork() {
        val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, locationListener);
        val location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        showLocation(location)
    }

    //获取经纬度
    private fun showLocation(location: Location?) {
        if (null ==  location) {
            getLocation()
            return
        }
        val latitude: Double = location.getLatitude() //纬度
        val longitude: Double = location.getLongitude() //经度
        getAddress(latitude, longitude)
    }

    private fun getAddress(latitude: Double, longitude: Double) {
        //Geocoder通过经纬度获取具体信息
        val gc = Geocoder(this, Locale.getDefault())
        try {
            val locationList: List<Address?>? = gc.getFromLocation(latitude, longitude, 1)
            if (locationList != null) {
                val address: Address? = locationList[0]
                val countryName: String? = address?.getCountryName() //国家
                val countryCode: String? = address?.getCountryCode()
                val adminArea: String? = address?.getAdminArea() //省
                val locality: String? = address?.getLocality() //市
                val subLocality: String? = address?.getSubLocality() //区
                val featureName: String? = address?.getFeatureName() //街道
                var i = 0
                Log.d(TAG, "countryName:$countryName countryCode:$countryCode " +
                            "adminArea:$adminArea locality:$locality " + "subLocality:$subLocality featureName:$featureName")
                while (address?.getAddressLine(i) != null) {
                    val addressLine: String = address.getAddressLine(i)
                    // eg. 街道名称:广东省深圳市罗湖区蔡屋围一街深圳瑞吉酒店
                    Log.d(TAG, "addressLine:$addressLine")
                    i++
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "getAddress error:" + e.message)
        }
    }

    private val locationListener = object :LocationListener {
        override fun onLocationChanged(location: Location) {
            Log.d(TAG, "onLocationChanged location:$location")
            showLocation(location);
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "onProviderEnabled provider:$provider")
        }

        override fun onProviderDisabled(provider: String) {
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
        }
    }

    private val newLocationListener = object :LocationListener {
        override fun onLocationChanged(location: Location) {
            Log.d(TAG, "onLocationChanged location:$location")
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "onProviderEnabled provider:$provider")
        }

        override fun onProviderDisabled(provider: String) {
            Log.d(TAG, "onProviderDisabled provider:$provider")
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "onStatusChanged provider:$provider status:$status extras:$extras")
        }
    }
}
